package com.snow.useviewdemo.util;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * Created by zhyt
 * Date: 2022/10/8
 * Describe:添加重试，retryWhen()
 */
public class RetryTimesFunction implements
        Function<Observable<? extends Throwable>, Observable<?>> {

    private final int maxRetries;
    private int retryCount = 0;
    private long delayDuration;

    /**
     * @param maxRetries    最大重试次数
     * @param delayDuration 每次重试间隔 单位毫秒
     */
    public RetryTimesFunction(int maxRetries, long delayDuration) {
        this.maxRetries = maxRetries;
        this.delayDuration = delayDuration;
    }

    @Override
    public Observable<?> apply(Observable<? extends Throwable> attempts) throws Exception {
        return attempts
                .flatMap((Throwable throwable) -> {
                    if (++retryCount <= maxRetries) {
                        return Observable.timer(delayDuration,
                                TimeUnit.MILLISECONDS);
                    }
                    return Observable.error(throwable);
                });
    }
}
